<?php
class main extends spController
{	
	function check(){
		import('weibooauth.php');
		$keys = spAccess('r', 'WEIBOKEY');
		$replys = spAccess('r', 'REPLYS');
		$c = new WeiboClient( WB_AKEY , 
	                      WB_SKEY , 
	                      $keys['oauth_token'] , 
	                      $keys['oauth_token_secret']  );
		$msg  = $c->mentions();
		if($msg === false || $msg === null) {
			echo "error occured";
			return false;
		}
		if (isset($msg['error_code']) && isset($msg['error'])){
			echo ('Error_code: '.$msg['error_code'].';  Error: '.$msg['error'] );
			return false;
		}
		foreach ($msg as $data){
			$id = number_format($data['id'],0,'','');
			$DONES = spAccess('r', 'DONES');
			if($DONES >= $id){
				continue;
			}
			$text = $data['text'];
			$default = TRUE;
			foreach ($replys as $k => $v){
				if(strpos($text, $k) !== FALSE){
					if($this -> reply($id,$v) === FALSE){
						return FALSE;
					}
					$default = FALSE;
				}
			}
			if($default){
				if($this -> reply($id,$replys[0]) === FALSE){
					return FALSE;
				}
			}
			spAccess('w', 'DONES', $id);
		}
	}
	
	private function reply($id,$text,$c){
		import('weibooauth.php');
		$keys = spAccess('r', 'WEIBOKEY');
		//Statuses/reply
		$c = new WeiboClient( WB_AKEY , 
		                      WB_SKEY , 
		                      $keys['oauth_token'] , 
		                      $keys['oauth_token_secret']  );
		//to be filled in
		$msg = $c->send_comment($id,urlencode($text.' '.mt_rand(0, 100)),null);
		if ($msg === false || $msg === null){
			echo "Error occured";
			return false;
		}
		if (isset($msg['error_code']) && isset($msg['error'])){
			echo ('Error_code: '.$msg['error_code'].';  Error: '.$msg['error'] );
			return false;
		}
		echo($msg['id'].' : '.$msg['text'].'  '.$msg['created_at']);
	}
}